package com.sigmatrix.h5.config;

import java.io.IOException;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.sigmatrix.h5.auth.DefaultAuthenticator;
import com.sigmatrix.h5.auth.LoginSession;

import net.logstash.logback.encoder.org.apache.commons.lang.StringUtils;


/**
 * 和top平台CurrentUser功能类似。为了区分用LoginUser类名前缀。
 * @author wei.wang
 *
 */
public class LoginUserMethodArgumentResolver implements HandlerMethodArgumentResolver {

	@Resource(name="defaultAuthenticator")
	private DefaultAuthenticator authenticator;

	public LoginUserMethodArgumentResolver() {
	}

	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		if (parameter.hasParameterAnnotation(LoginUser.class)) {
			return true;
		}
		return false;
	}

	@Override
	public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
			NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws IOException {
		LoginUser currentUserAnnotation = parameter.getParameterAnnotation(LoginUser.class);
		String token = webRequest.getHeader(currentUserAnnotation.value());
		if(StringUtils.isEmpty(token)){
			token = webRequest.getParameter(currentUserAnnotation.value());
		}
		if(StringUtils.isEmpty(token)){
			return null;			
		}
		LoginSession loginSession = authenticator.getLoginSession(token);
		if(loginSession!=null){
			return loginSession.getInfo();
		}

		return null;
	}
}
